'use client'

import { useState, useEffect } from 'react'
import { Search, Filter, Heart, Users, Clock, MapPin, ChevronDown, ChevronUp } from 'lucide-react'
import { demandApi, serviceApi } from '../../lib/api-client'
import { Demand, Service, User } from '../../lib/types'
import MatchRecommendations from '../../components/matching/MatchRecommendations'
import BottomNavigation from '../../components/layout/BottomNavigation'
import { useAuth } from '../../contexts/AuthContext'
import LoginPrompt from '../../components/auth/LoginPrompt'

// 定义共同属性接口
type MutualAidItem = Demand | Service

// 类型守卫函数
function checkIsDemand(item: any): item is Demand {
  return item && typeof item === 'object' && 'urgency' in item
}

function checkIsService(item: any): item is Service {
  return item && typeof item === 'object' && 'availableFrom' in item
}

type TabType = 'all' | 'demands' | 'services'

export default function MutualAidPage() {
  const [activeTab, setActiveTab] = useState<TabType>('all')
  const [searchQuery, setSearchQuery] = useState('')
  const [showFilters, setShowFilters] = useState(false)
  const [showHelp, setShowHelp] = useState(false)
  const [demands, setDemands] = useState<Demand[]>([])
  const [services, setServices] = useState<Service[]>([])
  const [loading, setLoading] = useState(true)
  const { isAuthenticated } = useAuth()

  // 从 API 获取数据 - 增强错误处理和重试机制
  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true)
        const [demandsData, servicesData] = await Promise.all([
          demandApi.getDemands(),
          serviceApi.getServices()
        ])

        // 数据验证和类型安全
        setDemands(Array.isArray(demandsData) ? demandsData : [])
        setServices(Array.isArray(servicesData) ? servicesData : [])
      } catch (error) {
        console.error('获取数据失败:', {
          error: error instanceof Error ? error.message : 'Unknown error',
          timestamp: new Date().toISOString()
        })

        // 设置空数据防止界面崩溃
        setDemands([])
        setServices([])
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [])

  // 过滤数据
  const filteredData: MutualAidItem[] = (activeTab === 'all'
    ? [...demands, ...services]
    : activeTab === 'demands'
      ? demands
      : services
  ).filter((item: MutualAidItem) => {
    if (!searchQuery) return true

    // 处理 tags 字段，可能是字符串数组或 JSON 字符串
    let tags: string[] = []
    if (item.tags) {
      if (typeof item.tags === 'string') {
        try {
          tags = JSON.parse(item.tags)
        } catch {
          tags = []
        }
      } else if (Array.isArray(item.tags)) {
        tags = item.tags
      }
    }

    return (
      item.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      item.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
      tags.some((tag: string) => tag.toLowerCase().includes(searchQuery.toLowerCase()))
    )
  })

  const getUrgencyColor = (urgency: number) => {
    switch (urgency) {
      case 5: return 'bg-red-100 text-red-800'
      case 4: return 'bg-orange-100 text-orange-800'
      case 3: return 'bg-yellow-100 text-yellow-800'
      default: return 'bg-gray-100 text-gray-800'
    }
  }

  const getTypeColor = (type: string) => {
    switch (type.toLowerCase()) {
      case 'emergency': return 'bg-red-100 text-red-800'
      case 'repair': return 'bg-blue-100 text-blue-800'
      case 'care': return 'bg-green-100 text-green-800'
      case 'shopping': return 'bg-purple-100 text-purple-800'
      case 'moving': return 'bg-orange-100 text-orange-800'
      case 'learning': return 'bg-indigo-100 text-indigo-800'
      case 'teaching': return 'bg-indigo-100 text-indigo-800'
      default: return 'bg-gray-100 text-gray-800'
    }
  }

  const formatTime = (date: Date | string) => {
    const dateObj = typeof date === 'string' ? new Date(date) : date
    const now = new Date()
    const diff = now.getTime() - dateObj.getTime()

    if (diff < 60 * 60 * 1000) {
      return `${Math.floor(diff / (60 * 1000))}分钟前`
    } else if (diff < 24 * 60 * 60 * 1000) {
      return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
    } else {
      return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`
    }
  }

  const getTypeDisplayName = (type: string) => {
    switch (type.toLowerCase()) {
      case 'emergency': return '紧急求助'
      case 'repair': return '维修服务'
      case 'care': return '照看服务'
      case 'shopping': return '代购服务'
      case 'moving': return '搬运服务'
      case 'learning': return '学习辅导'
      case 'general': return '一般服务'
      case 'teaching': return '教学服务'
      default: return type
    }
  }

  return (
    <div className="min-h-screen bg-gray-50 pb-20">
      {/* 顶部搜索栏 - 响应式 */}
      <div className="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-10">
        <div className="responsive-container py-3 sm:py-4">
          <div className="flex items-center gap-2 sm:gap-4 mb-3 sm:mb-4">
            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 sm:w-5 sm:h-5" />
              <input
                type="text"
                placeholder="搜索需求或服务..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full pl-9 sm:pl-10 pr-4 py-2 sm:py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 text-base sm:text-lg"
              />
            </div>
            <button
              onClick={() => setShowFilters(!showFilters)}
              className="p-2 sm:p-3 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
            >
              <Filter className="w-4 h-4 sm:w-5 sm:h-5 text-gray-600" />
            </button>
          </div>

          {/* 标签栏 - 响应式 */}
          <div className="flex gap-1 sm:gap-2 overflow-x-auto pb-1 sm:pb-2">
            {(['all', 'demands', 'services'] as TabType[]).map((tab) => (
              <button
                key={tab}
                onClick={() => setActiveTab(tab)}
                className={`px-3 sm:px-4 py-1 sm:py-2 rounded-full text-xs sm:text-sm font-medium whitespace-nowrap transition-colors ${
                  activeTab === tab
                    ? 'bg-primary-600 text-white'
                    : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                }`}
              >
                {tab === 'all' && '全部'}
                {tab === 'demands' && '求助需求'}
                {tab === 'services' && '提供服务'}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* 主内容区 - 响应式 */}
      <main className="responsive-container py-4 sm:py-6">
        {/* 智能匹配推荐 */}
        <div className="mb-6 sm:mb-8">
          <MatchRecommendations
            type="demand"
            demandId="d1"
            limit={3}
          />
        </div>

        {loading ? (
          <div className="text-center py-8 sm:py-12">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mx-auto"></div>
            <p className="text-gray-500 mt-4">加载中...</p>
          </div>
        ) : filteredData.length === 0 ? (
          <div className="text-center py-8 sm:py-12">
            <Heart className="w-12 h-12 sm:w-16 sm:h-16 text-gray-300 mx-auto mb-3 sm:mb-4" />
            <h3 className="text-lg sm:text-xl font-semibold text-gray-600 mb-1 sm:mb-2">暂无相关内容</h3>
            <p className="text-gray-500 text-sm">尝试调整搜索条件或查看其他分类</p>
          </div>
        ) : (
          <div className="space-y-3 sm:space-y-4">
            {filteredData.map((item) => {
              const isDemand = checkIsDemand(item)

              // 处理 tags 字段，可能是字符串数组或 JSON 字符串
              let tags: string[] = []
              if (item.tags) {
                if (typeof item.tags === 'string') {
                  try {
                    tags = JSON.parse(item.tags)
                  } catch {
                    tags = []
                  }
                } else if (Array.isArray(item.tags)) {
                  tags = item.tags
                }
              }

              return (
                <div key={item.id} className="card hover:shadow-lg transition-shadow duration-200">
                  <div className="flex items-start gap-3 sm:gap-4">
                    {/* 用户头像 - 响应式大小 */}
                    <div className="flex-shrink-0">
                      <div className="w-10 h-10 sm:w-12 sm:h-12 bg-primary-100 rounded-full flex items-center justify-center">
                        <Users className="w-5 h-5 sm:w-6 sm:h-6 text-primary-600" />
                      </div>
                    </div>

                    {/* 内容区域 */}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-start justify-between mb-1 sm:mb-2">
                        <h3 className="text-base sm:text-lg font-semibold text-gray-900 truncate">
                          {item.title}
                        </h3>
                        {isDemand && (
                          <span className={`px-2 py-1 rounded-full text-xs font-medium ${getUrgencyColor(item.urgency)}`}>
                            紧急{item.urgency}级
                          </span>
                        )}
                      </div>

                      <p className="text-gray-600 text-xs sm:text-sm mb-2 sm:mb-3 line-clamp-2">
                        {item.description}
                      </p>

                      {/* 标签 - 响应式 */}
                      <div className="flex flex-wrap gap-1 sm:gap-2 mb-2 sm:mb-3">
                        <span className={`px-2 py-1 rounded-full text-xs font-medium ${getTypeColor(item.type)}`}>
                          {getTypeDisplayName(item.type)}
                        </span>
                        {tags.slice(0, 3).map((tag: string, index: number) => (
                          <span key={index} className="px-2 py-1 bg-gray-100 text-gray-700 rounded-full text-xs">
                            {tag}
                          </span>
                        ))}
                      </div>

                      {/* 底部信息 - 响应式 */}
                      <div className="flex flex-col sm:flex-row sm:items-center justify-between text-xs sm:text-sm text-gray-500 gap-1 sm:gap-0">
                        <div className="flex items-center gap-2 sm:gap-4">
                          <span className="flex items-center gap-1">
                            <MapPin className="w-3 h-3 sm:w-4 sm:h-4" />
                            {item.locationText || '未知位置'}
                          </span>
                          <span className="flex items-center gap-1">
                            <Clock className="w-3 h-3 sm:w-4 sm:h-4" />
                            {formatTime(item.createdAt)}
                          </span>
                        </div>
                        <span className="text-primary-600 font-medium">
                          {item.user?.name || '匿名用户'}
                        </span>
                      </div>
                    </div>
                  </div>

                  {/* 操作按钮 - 响应式 */}
                  <div className="mt-3 sm:mt-4 pt-3 sm:pt-4 border-t border-gray-200 flex flex-col sm:flex-row gap-2 sm:gap-3">
                    {isAuthenticated ? (
                      <>
                        <button className="bg-primary-600 hover:bg-primary-700 text-white py-2 sm:py-3 px-3 sm:px-4 rounded-lg text-center text-sm sm:text-base font-medium transition-colors">
                          联系TA
                        </button>
                        {isDemand && (
                          <button className="bg-green-600 hover:bg-green-700 text-white py-2 sm:py-3 px-3 sm:px-4 rounded-lg text-center text-sm sm:text-base font-medium transition-colors">
                            我能帮忙
                          </button>
                        )}
                      </>
                    ) : (
                      <div className="w-full text-center">
                        <p className="text-sm text-gray-500 mb-2">请先登录以联系邻居</p>
                        <a href="/" className="inline-block bg-primary-600 hover:bg-primary-700 text-white py-2 px-4 rounded-lg text-sm font-medium transition-colors">
                          立即登录
                        </a>
                      </div>
                    )}
                  </div>
                </div>
              )
            })}
          </div>
        )}
      </main>

      {/* 使用提示 - 响应式 */}
      <div className="fixed bottom-20 left-2 right-2 sm:left-4 sm:right-4 bg-blue-50 border border-blue-200 rounded-lg text-xs sm:text-sm text-blue-800">
        <button
          onClick={() => setShowHelp(!showHelp)}
          className="w-full p-3 sm:p-4 flex items-center justify-between hover:bg-blue-100 transition-colors rounded-lg"
        >
          <h4 className="font-semibold">使用提示</h4>
          {showHelp ? (
            <ChevronUp className="w-3 h-3 sm:w-4 sm:h-4" />
          ) : (
            <ChevronDown className="w-3 h-3 sm:w-4 sm:h-4" />
          )}
        </button>

        {showHelp && (
          <div className="px-3 sm:px-4 pb-3 sm:pb-4">
            <ul className="space-y-1">
              <li>• 点击"联系TA"开始与邻居沟通</li>
              <li>• 紧急需求会显示红色标签</li>
              <li>• 可以根据类型筛选查看</li>
              {!isAuthenticated && (
                <li>• 请先登录以联系邻居和发布需求</li>
              )}
            </ul>
          </div>
        )}
      </div>

      {/* 底部导航 */}
      <BottomNavigation />

      {/* 未登录提示 */}
      {!isAuthenticated && (
        <LoginPrompt message="请先登录以联系邻居和发布需求" />
      )}
    </div>
  )
}